const express = require("express");
const router = express.Router();
const { db, genid } = require("../db/DbUtils");

// 列表查询

router.get("/list", async (req, res) => {
  const select_sql = "SELECT * FROM `category`";
  let { err, rows } = await db.async.all(select_sql);
  if (err == null) {
    res.send({
      code: 200,
      msg: "查询成功",
      data: rows,
    });
  } else {
    res.send({
      code: 500,
      msg: "查询失败",
    });
  }
});

// 删除接口
router.delete("/_token/delete", async (req, res) => {
  let id = req.query.id;
  const delete_sql = "DELETE FROM `category` WHERE `id` = ?";
  let { err, rows } = await db.async.run(delete_sql, [id]);
  if (err == null) {
    res.send({
      code: 200,
      msg: "删除成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "添加失败",
    });
  }
});

// 添加接口
router.post("/_token/add", async (req, res) => {
  const { name } = req.body;
  const categoryId = genid.NextId();
  const insert_sql = "INSERT INTO `category` (`id`,`name`) VALUES (?,?)";

  const isNotExist = await categoryIsNotExist(name);
  if (isNotExist) {
    let { err, rows } = await db.async.run(insert_sql, [categoryId, name]);
    if (err == null) {
      res.send({
        code: 200,
        msg: "添加成功",
        data: {
          name,
          id: categoryId,
        },
      });
    } else {
      res.send({
        code: 500,
        msg: "添加失败",
        data: null,
      });
    }
  } else {
    res.send({
      code: 500,
      msg: "该分类已存在",
      data: null,
    });
  }
});

// 修改接口
router.put("/_token/update", async (req, res) => {

  let { id, name } = req.body;
  const update_sql = "UPDATE `category` SET `name` = ? WHERE `id` = ?";

  const isNotExist = await categoryIsNotExist(name);
  if (isNotExist) {
    let { err, rows } = await db.async.run(update_sql, [name, id]);

    if (err == null) {
      res.send({
        code: 200,
        msg: "修改成功",
        data: {
          name,
          id,
        },
      });
    } else {
      res.send({
        code: 500,
        msg: "修改失败",
        data: {},
      });
    }
  } else {
    res.send({
      code: 500,
      msg: "该分类已存在",
    });
  }
});

// 判断是否已存在该分类
function categoryIsNotExist(name) {
  return new Promise(async (resolve, reject) => {
    const select_sql = "SELECT * FROM `category` WHERE `name` = ? ";
    // 查询是否已存在该分类
    let { err, rows } = await db.async.all(select_sql, [name]);

    // 该分类不存在
    if (err == null && rows.length === 0) {
      resolve(true);
    } else {
      resolve(false);
    }
  });
}

module.exports = router;
